package trans

import (
	"encoding/json"
	lsql "jujiu/data/persist/mysql"
	"jujiu/redis"
	"log"
)

func Dispatch2Redis(delFlag bool) {
	data := getStandradData()
	if data == nil {
		log.Println("数据为空")
		return
	}
	for key, vle := range redis.RedisMap {
		log.Println(key, " doing ")
		// 清除现有的缓存
		if delFlag {
			log.Println("del data ...")
			vle.Del("TEXT_LANGUAGE_INFO")
		}
		// 同步现有的数据
		vle.SAdd("TEXT_LANGUAGE_INFO", data)
		log.Println(key, "done")

	}
}

func convert(texts []lsql.TransLgeTextDO) (map[string]lsql.LangeDO) {
	lgemap := make(map[string]lsql.LangeDO)
	for _, vle := range texts {
		lgeDO := lsql.LangeDO{}
		lgeDO.Text = vle.Text
		lgeDO.Type = vle.LgeCode
		lgemap[vle.LgeCode] = lgeDO
	}
	return lgemap
}

func getStandradData() ([] string) {
	// 获取数据
	clinet := lsql.DataSourceClientMap["cn_real_ioe"]
	mapper := lsql.NewTransLgeTextMapper(&clinet)
	allTexts, e := mapper.QueryAll()
	if e != nil {
		log.Println("查询失败！", e)
		return nil
	}
	// 处理数据
	txtmap := make(map[string][]lsql.TransLgeTextDO)
	for _, vle := range allTexts {
		vleList := txtmap[vle.TransCode]
		dos := append(vleList, vle)
		txtmap[vle.TransCode] = dos
	}
	var textInfostr [] string
	for k, v := range txtmap {
		textInfoDO := lsql.TextInfoDO{}
		textInfoDO.LanguageDOMap = convert(v)
		textInfoDO.Code = k
		bytes, _ := json.Marshal(textInfoDO)
		textInfostr = append(textInfostr, string(bytes))
	}
	return textInfostr
}
